var leads = new Array();		
var rowCounter1 = 1;	
var rowCounter2 = 1;	
var suggestionsAdded = 0;
var localSuggSearch

// TODO : fix copypaste between functions 1 + 2
// TODO : add marker information window
// TODO : hide zoom control for this window
	
	function createSuggTab() {
		document.getElementById(suggestionsTabId).innerHTML = '<table width="100%" id="header" class="sb-result">'+
													    	  '<td class="sb-row"></td>'+
														      '<td class="sb-header">Show me the best ' +
														      "<select id='suggRes1' onchange='initSuggestionsTable1()'>"+
																'<OPTION SELECTED VALUE="3">3</OPTION>'+
																'<OPTION VALUE="5">5</OPTION>'+
																'<OPTION VALUE="10">10</OPTION>'+
															  "</select> results<br>"+
															  '<b>Suggestions based on your friends choices:</b></td></table>';
		document.getElementById(suggestionsTabId).innerHTML += '<div id="tablediv1"></div>';
		

		document.getElementById(suggestionsTabId).innerHTML += '<table width="100%" id="header" class="sb-result">'+
													    	  '<td class="sb-row"></td>'+
														      '<td class="sb-header">Show me the best ' +
														      "<select id='suggRes2' onchange='initSuggestionsTable2()'>"+
																'<OPTION SELECTED VALUE="3">3</OPTION>'+
																'<OPTION VALUE="5">5</OPTION>'+
																'<OPTION VALUE="10">10</OPTION>'+
															  "</select> results<br>"+
															  '<b>Suggestions based on people with similar choices:</b></td></table>';								  
		document.getElementById(suggestionsTabId).innerHTML += '<div id="tablediv2"></div>';
			
		initSuggestionsTable1();
		initSuggestionsTable2();
	}	
	
	
	
function initSuggestionsTable1() {
		url = "http://www.cs.tau.ac.il/~hilacoh1/images/ajax-load.gif";
		rowCounter1 = 1;									
		document.getElementById("tablediv1").innerHTML =   		   '<table width="100%"><tr><td valign="top">'
																	+'<table id="dataheader" class="sb-result">'
																	+	'<td class="sb-row"></td>'
																	+	'<td class="sb-title">Name</td>'
																	+	'<td class="sb-address">Address</td>'
																	+	'<td class="sb-phone">Phone</td>'
																	+ '</table>'
																	+  '<div id="saved_results1" class="visible"><img src='+url+' id="loader1"/></div>'
																	+  '<div id="lead_map" class="invisible">Map</div>'
																	+ '</td></tr></table>';
		openSocialReq(suggestByfriends);	
}

function initSuggestionsTable2() {
		url = "http://www.cs.tau.ac.il/~hilacoh1/images/ajax-load.gif";
		rowCounter2 = 1;									
		document.getElementById("tablediv2").innerHTML =   		   '<table width="100%"><tr><td valign="top">'
																	+'<table id="dataheader" class="sb-result">'
																	+	'<td class="sb-row"></td>'
																	+	'<td class="sb-title">Name</td>'
																	+	'<td class="sb-address">Address</td>'
																	+	'<td class="sb-phone">Phone</td>'
																	+ '</table>'
																	+  '<div id="saved_results2" class="visible"><img src='+url+' id="loader2"/></div>'
																	+  '<div id="lead_map" class="invisible">Map</div>'
																	+ '</td></tr></table>';

		requestOwnderUid(suggestBySimilarPeople);
}




function suggestBySimilarPeople(response) {
	
	var uid = response.get('owner').getData().getId();
	var select = document.getElementById('suggRes2');
	var numOfRes = select.options[select.selectedIndex].value;
	var params = {};
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	var url = GLOBAL_BASE_URL + '/suggestions';
	
	postData = gadgets.io.encodeValues({
		'method'  : '1',
		'numberOfResults' : numOfRes,
		'ownerUid' : uid
	});

	params[gadgets.io.RequestParameters.POST_DATA] = postData;
	gadgets.io.makeRequest(url, showSuggestedSites2, params);
}
	

function suggestByfriends(response) {

	var friends = response.get('get_friends').getData(); 		
	var friendsList = [];
	var select = document.getElementById('suggRes1');
	var numOfRes = select.options[select.selectedIndex].value;
	friends.each(function(person) 
	{
		friendsList.push(person.getId());
	})
		
	var params = {};
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	var url = GLOBAL_BASE_URL + '/suggestions';
	
	postData = gadgets.io.encodeValues({
		'method'  : '0',
		'numberOfResults' : numOfRes,
		'friends' : friendsList
	});

	params[gadgets.io.RequestParameters.POST_DATA] = postData;
	gadgets.io.makeRequest(url, showSuggestedSites1, params);
}


function showSuggestedSites2(response) {

	localSuggSearch2 = new google.search.LocalSearch();
	var suggestions = gadgets.json.parse(response.data);

	for (var i = 0; i < suggestions.length; i++)
	{	
		localSuggSearch2.setCenterPoint(new GLatLng(suggestions[i].info.lat, suggestions[i].info.lng));
		localSuggSearch2.setSearchCompleteCallback(this, addToTable2);
		localSuggSearch2.execute(suggestions[i].info.name);
	}
	if (suggestions.length == 0) {
		displayNoResults(2);
	}
}


function displayNoResults(method) {

	var t = createTable("sb-result");
	var tr = createTableRow(t);


	if (method == 1) {
	document.getElementById("loader1").style.display="none";
	url = "http://www.google.com/ig/c/ui/ContactManager?titleBar=false";
	var str = "No suggestions were found for you.<br>You should add more friends to Google Sandbox by clicking " 
			+  "<a href='"+url+"' target='_blank'>here </a>";
	var savedResults = document.getElementById("saved_results1");
	}
	if (method == 2) {
	document.getElementById("loader2").style.display="none";
	url = "";
	var str = "No suggestions were found for you.<br>You should go out more :) Click the Search Tab to view the current top popular places.";
	 var savedResults = document.getElementById("saved_results2");
	}
	if (method == 3) {
		var str = "No plans were made yet ";
		var savedResults = document.getElementById("Friendresults");
	}
	
	tr.innerHTML = str;	
	savedResults.appendChild(t);
}

function showSuggestedSites1(response) {	

	localSuggSearch1 = new google.search.LocalSearch();
	var suggestions = gadgets.json.parse(response.data);
	for (var i = 0; i < suggestions.length; i++)
	{	
		localSuggSearch1.setCenterPoint(new GLatLng(suggestions[i].info.lat, suggestions[i].info.lng));
		localSuggSearch1.setSearchCompleteCallback(this, addToTable1);
		localSuggSearch1.execute(suggestions[i].info.name);
	}
	if (suggestions.length == 0) {
		displayNoResults(1);
	}
}


function addToTable1() {
	
	var result = localSuggSearch1.results[0];
	
	var t = createTable("sb-result");
	var tr = createTableRow(t);
	var rowCell = createTableCell(tr,"sb-row");
	var titleCell = createTableCell(tr,"sb-title");
	var addressCell = createTableCell(tr,"sb-address");
	var phoneCell = createTableCell(tr,"sb-phone");
	
	// remove loading animation
	if (rowCounter1 == 1) 
		document.getElementById("loader1").style.display="none";
	
	var str = rowCounter1++;
	rowCell.innerHTML = str;

	str = "<a href='"+result.url+"' target='_blank'>" + result.titleNoFormatting + "</a>";
	titleCell.innerHTML = str;

	str = result.streetAddress + ", " + result.city + " " + result.region;
	addressCell.innerHTML = str;

	if (result.phoneNumbers && result.phoneNumbers.length > 0) {
	  str = result.phoneNumbers[0].number;
	} else {
	  str = "unknown";
	}
	phoneCell.innerHTML = str;

	// attach it
	var savedResults = document.getElementById("saved_results1");
	savedResults.appendChild(t);

	leads.push(result);
	var thispoint = new google.maps.LatLng(parseFloat(result.lat), parseFloat(result.lng));
    var thismarker = new GMarker(thispoint,{icon:createSuggestionsIcon()});
    thismarker._lead_ = result;
	thismarker.mycategory = "suggestions"; 
    allMarkers.push(thismarker);
    map.addOverlay(thismarker);
	if (document.getElementById("suggestionsbox").checked == false) {
		thismarker.hide();
	}
}


function addToTable2() {
	
	var result = localSuggSearch2.results[0];
	
	var t = createTable("sb-result");
	var tr = createTableRow(t);
	var rowCell = createTableCell(tr,"sb-row");
	var titleCell = createTableCell(tr,"sb-title");
	var addressCell = createTableCell(tr,"sb-address");
	var phoneCell = createTableCell(tr,"sb-phone");

	// remove loading animation
	if (rowCounter2 == 1) 
		document.getElementById("loader2").style.display="none";
	
	var str = rowCounter2++;
	rowCell.innerHTML = str;

	str = "<a href='"+result.url+"' target='_blank'>" + result.titleNoFormatting + "</a>";
	titleCell.innerHTML = str;

	str = result.streetAddress + ", " + result.city + " " + result.region;
	addressCell.innerHTML = str;

	if (result.phoneNumbers && result.phoneNumbers.length > 0) {
	  str = result.phoneNumbers[0].number;
	} else {
	  str = "unknown";
	}
	phoneCell.innerHTML = str;

	// attach it
	var savedResults = document.getElementById("saved_results2");
	savedResults.appendChild(t);

	leads.push(result);
	var thispoint = new google.maps.LatLng(parseFloat(result.lat), parseFloat(result.lng));
    var thismarker = new GMarker(thispoint,{icon:createSuggestionsIcon()});
    thismarker._lead_ = result;
	thismarker.mycategory = "suggestions"; 
	allMarkers.push(thismarker);
    map.addOverlay(thismarker);
	if (document.getElementById("suggestionsbox").checked == false) {
		thismarker.hide();
	}
}


function createTable(opt_className) {
	var el = document.createElement("table");
	if (opt_className) { el.className = opt_className; }
	return el;
}

function createTableRow(table) {
	var tr = table.insertRow(-1);
	return tr;
}

function createTableCell(tr, opt_className) {
	var td = tr.insertCell(-1);
	if (opt_className) { td.className = opt_className; }
	return td;
}


function requestOwnderUid(func) {
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'owner');
	req.send(func);
}

		
function createSuggestionsIcon() {return createCustomIcon("purple");}

